package com.example.flashsales.Tools;

import com.example.flashsales.Factory;
import com.example.flashsales.service.impl.OrderServiceImpl;
import com.example.flashsales.service.impl.ZhekouServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 订单取消的定时器 一秒中一次（30分钟未支付就删除订单）
 */
@Component
@Slf4j
public class TimerTools {

    @Autowired
    OrderServiceImpl orderService;

    @Autowired
    ZhekouServiceImpl zhekouService;

    Factory factory = Factory.getFactory();

//    @Scheduled(cron = "*/1 * * * * ?")
    public void deleteOrder(){
        final List<Long> delete = orderService.delete();
        if (delete != null){
            for (Long aLong : delete) {
                log.info("删除订单->"+aLong);
            }
        }

    }


    /**
     * 判断用户是否在线
     * @throws ParseException
     */
    @Scheduled(cron = "*/1 * * * * ?")
    public void offlineUser() throws ParseException {
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Long aLong : factory.getOnlineUsers().keySet()) {
            if (simpleDateFormat.parse(factory.getOnlineUsers().get(aLong).getData()).getTime() < (new Date().getTime() - 1000*60*30)){
                factory.getOnlineUsers().remove(aLong);
                log.info("下线的用户->"+aLong);
            }
        }

    }

    /**
     * 每天凌晨判断卷是否过期
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void updateVolume(){
        final List<Long> longs = zhekouService.changeVolume();
        if (longs != null){
            for (Long aLong : longs) {
                log.info("过期卷->"+aLong);
            }
        }
    }
}
